package com.wangjie.doublepointer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jieshao
 * @date 2022/4/20 11:41
 *
 * 3. 无重复字符的最长子串
 */
public class Test04 {
    public static void main(String[] args) {
        String s = "abcabcbb";
        int res = lengthOfLongestSubstring(s);
        System.out.println("res:" + res);
    }

    public static int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> window = new HashMap<>();
        int left = 0;
        int right = 0;
        // 记录结果
        int res = 0;
        while (right < s.length()) {
            char c = s.charAt(right);
            right++;
            // 进行窗口内数据的一系列更新
            window.put(c, window.getOrDefault(c, 0) + 1);
            // 判断左侧窗口是否需要收缩(大于 1 说明窗口中存在重复字符)
            while (window.get(c) > 1) {
                char d = s.charAt(left);
                left++;
                // 进行窗口内数据的一系列更新
                window.put(d, window.getOrDefault(d, 0) - 1);
            }
            res = Integer.max(res, right - left);
        }
        return res;
    }
}